package experimentSecond;

import java.util.*;

class HRNScheduler {
    private List<Job> jobList; // 作业列表

    // 构造函数
    public HRNScheduler() {
        jobList = new ArrayList<>();
    }

    // 添加作业
    public void addJob(Job job) {
        jobList.add(job);
    }
    public void addJobs(Job[] jobsArray){
        jobList.addAll(Arrays.asList(jobsArray));
    }

    // 计算响应比
    private double calculateResponseRatio(Job job, int currentTime) {
        int waitingTime = currentTime - job.arrivalTime;
        return (double) (waitingTime + job.burstTime) / job.burstTime;
    }

    // HRN调度算法
    public void schedule() {
        int currentTime = 0;
        int completedJobs = 0;
        int n = jobList.size();

        while (completedJobs < n) {
            Job nextJob = null;
            double highestResponseRatio = -1;

            // 选择响应比最高的作业
            for (Job job : jobList) {
                if (job.status == 'W' && job.arrivalTime <= currentTime) {
                    double responseRatio = calculateResponseRatio(job, currentTime);
                    if (responseRatio > highestResponseRatio) {
                        highestResponseRatio = responseRatio;
                        nextJob = job;
                    }
                }
            }

            if (nextJob != null) {
                // 执行选中的作业
                currentTime += nextJob.burstTime;
                nextJob.finishTime = currentTime;
                nextJob.status = 'F'; // 标记为已完成
                completedJobs++;
            } else {
                // 如果没有作业可以执行，时间前进
                currentTime++;
            }
        }

        for (Job job : jobList) {
            job.printJobInfo();
        }
    }
}